from flask import Flask, request, jsonify, session, send_from_directory
from http import HTTPStatus
from dashscope import Application
import threading
import uuid
import os
import json
from datetime import datetime

app = Flask(__name__)
app.secret_key = 'your_secret_key'  # 用于加密 session

# 读取 config.json
with open('config.json') as config_file:
    config = json.load(config_file)

# 调用 agent app 的函数
def call_agent_app(prompt):
    response = Application.call(app_id=config['app_id'],
                                prompt=prompt,
                                api_key=config['api_key']
                                )
    if response.status_code != HTTPStatus.OK:
        return f'错误: request_id={response.request_id}, code={response.status_code}, message={response.message}'
    else:
        return response.output.text

# 存储对话内容
chat_histories = {}

def log_chat(session_id, user_message, bot_response):
    log_dir = 'logs'
    if not os.path.exists(log_dir):
        os.makedirs(log_dir)
    log_file = os.path.join(log_dir, f"{datetime.now().strftime('%Y-%m-%d')}.log")
    with open(log_file, 'a', encoding='utf-8') as f:
        f.write(f"Session ID: {session_id}\n")
        f.write(f"User: {user_message}\n")
        f.write(f"Bot: {bot_response}\n")
        f.write("\n")

@app.route('/')
def home():
    return send_from_directory('.', 'static/index.html')

@app.route('/send', methods=['POST'])
def send():
    if 'session_id' not in session:
        session['session_id'] = str(uuid.uuid4())
    session_id = session['session_id']
    if session_id not in chat_histories:
        chat_histories[session_id] = []
        # 添加开场白
        chat_histories[session_id].append({'user': '', 'response': '我是钱塘区招生咨询助手，你可以问我钱塘区学校的学区、学校电话、插班政策等各种问题，我会努力解答您的问题。'})
    prompt = request.form['prompt']
    chat_histories[session_id].append({'user': prompt, 'response': '请等待...'})

    # 开启线程处理大模型的回复
    thread = threading.Thread(target=update_response, args=(session_id, prompt))
    thread.start()
    
    return jsonify(chat_history=chat_histories[session_id])

@app.route('/get_responses', methods=['GET'])
def get_responses():
    if 'session_id' not in session:
        session['session_id'] = str(uuid.uuid4())
    session_id = session['session_id']
    if session_id not in chat_histories:
        chat_histories[session_id] = []
        # 添加开场白
        chat_histories[session_id].append({'user': '', 'response': '我是钱塘区招生咨询助手，你可以问我钱塘区学校的学区、学校电话、插班政策等各种问题，我会努力解答您的问题。'})
    return jsonify(chat_history=chat_histories[session_id])

def update_response(session_id, prompt):
    response = call_agent_app(prompt)
    for message in chat_histories[session_id]:
        if message['user'] == prompt and message['response'] == '请等待...':
            message['response'] = response
            break
    log_chat(session_id, prompt, response)

@app.route('/static/<path:filename>')
def serve_static(filename):
    return send_from_directory('static', filename)

if __name__ == '__main__':
    from waitress import serve
    serve(app, host='0.0.0.0', port=5000)
